import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_demo/scaffold/net/cm_api_interface.dart';
import 'package:flutter_demo/scaffold/net/dto/cm_response.dart';
import 'package:get/get.dart';

import 'dto/cm_user_login_response.dart';

/**
 * 接口请求
 */
class CMApi implements ICMApi {
  final _dio = Dio();

  static Type typeOf<T>() => T;

  CMApi() {
    _dio.options.baseUrl = "http://y-dev.camera360.com";
  }

  void demo() async {
    print("xxxxxxxxxxx");
    final response = await _dio.get('https://dart.dev');
    print(response);
  }

  /// [dataDecoder]
  Future<CMBaseResponse<T>> _post<T>({
    required String path,
    Object? data,
    Map<String, dynamic>? queryParameters,
    // required T Function(dynamic value) dataDecoder,
  }) async {
    final httpResp = await _dio.post(path, data: data, queryParameters: queryParameters);

    if (httpResp.statusCode == 200) {
      var baseResponse = CMBaseResponse<T>.fromJson(httpResp.data);
      // baseResponse.data = dataDecoder.call(httpResp.data['data']);
      var type = typeOf<T>();
      switch (type) {
        case CMUserLoginDto:
          baseResponse.data = CMUserLoginDto.fromJson(httpResp.data['data']) as T?;
          break;
        default:
          print("type : $type 不支持自动解析json，需要实现, \n ${StackTrace.current}");
      }

      return baseResponse;
    } else {
      return CMBaseResponse.netError(httpResp);
    }
  }

  @override
  Future<CMBaseResponse<CMUserLoginDto>> loginWithCode({required String mobile, required String code}) async {
    final response = await _post<CMUserLoginDto>(path: "/client/user/login", queryParameters: {'mobile': mobile, 'code': code});
    return response;
  }

  @override
  Future<CMBaseResponse<CMUserLoginDto>> loginWithPwd({required String mobile, required String pwd}) async {
    // path: "/client/user/pwd-login", queryParameters: {'mobile': mobile, 'pwd': pwd}, dataDecoder: (value) => CMUserLoginDto.fromJson(value));
    final response = await _post<CMUserLoginDto>(path: "/client/user/pwd-login", queryParameters: {'mobile': mobile, 'pwd': pwd});
    return response;
  }

  @override
  Future<CMBaseResponse<CMBaseResponse>> loginWith({required String mobile, required String pwd}) async {
    // path: "/client/user/pwd-login", queryParameters: {'mobile': mobile, 'pwd': pwd}, dataDecoder: (value) => CMUserLoginDto.fromJson(value));
    final response = await _post<CMBaseResponse>(path: "/client/user/pwd-login", queryParameters: {'mobile': mobile, 'pwd': pwd});
    return response;
  }
}
